import dayjs from 'dayjs';
import { ref, computed, getCurrentInstance, inject, onMounted, watch } from 'vue';
// import { computerPeriod } from '@modules/rpm/utils';
// const computerPeriod = tyRoot.getExportResource('src/modules/rpm/utils/index.js');
const computerPeriod = (startDate, endDate) => {
  if (!startDate || !endDate) return 0;
  const start = dayjs(startDate);
  const end = dayjs(endDate);
  return end.diff(start, 'day');
};
import { pick } from 'lodash';
import basic from '@common/basic';
import axios from 'axios';
const useQueryTypeByTypeDefName = basic.getExportResource('@/basic/utils/index.js').default;
import core from '@common/core'
const request = core.getExportResource('src/core/utils/http-tools.js').default;
 // 将代码包裹在异步函数中（如果尚未在异步环境中）
async function fetchStatusOptions() {
    try {
        const res = await request({
            method: 'get',
            url: '/rest/v1/devorder/checkUser',
            headers: {
                authorization: sessionStorage.getItem('authorization')
            }
        });
        if (res.data) {
            const statusOptions = res.data.data; // 正确赋值
            console.log(statusOptions);
            return statusOptions; // 返回获取的数据
        } else {
            const statusOptions = res.data.data; // 正确赋值
            console.log(statusOptions);
            return statusOptions; // 返回获取的数据
        }
    } catch (error) {
        console.error('请求错误:', error);
        return false; // 错误时返回null
    }
}

// 使用示例
export const isPMO = await fetchStatusOptions();
// 创建 props
export const createProps = (op = {}) => ({
  isMy: {
    type: Boolean,
    default: false
  },
  ...op
});

// 创建 props
export const createEmits = (op = []) => [...op];
export const useProjectLib = props => {
  const { commandFunc } = inject('apiFunTools');
  const { proxy } = getCurrentInstance();
  const { calcResult2, getPermByTableData, wujieName } = window.$wujie?.props || {};
  // 表格操作配置
  const operates = ref(['search', 'refresh', 'advanced', 'column']);
  // 表格列配置视图类型

  // 通过类型获取类型详情
  const { getTypeList } = useQueryTypeByTypeDefName();
  const searchTypeList = ref([]);
  const isNewProject = ref(false);
  const types = computed(() => {
    return isNewProject.value
      ? ['ty.inteplm.project.CTyProject']
      : ['ty.inteplm.project.CTyProject', 'ty.projectmng.admin.CTyPlan'];
  });
  const isCheckViewPermission = computed(() => {
    return javaPdm?.CHECKED_PROJECT_VIEW_PERMISSION;
  });

  const defaultCondition = ref([
    {
      propertyName: 'name',
      propertyValue: ''
    },
    {
      propertyName: 'projectNumber',
      propertyValue: ''
    },
    {
      propertyName: 'completionStatus',
      propertyValue: ''
    }
  ]);
  const sortColumns = ref([
    'name',
    'completionStatus',
    'percentWorkComplete',
    'category',
    'startDate',
    'finishDate',
    'finishDateDeff',
    'createstamp'
  ]);
  // 项目类型

  const operation = ref(props.isMy ? 'myParticipate' : '');
  const table = ref(null);
  const projectCreateRef = ref(null);
  const projectCreateOptions = ref({
    isDrawer: true,
    appendToBody: true,
    hideFooter: false,
    draggable: false,
    size: 600,
    confirmLoading: false,
    title: proxy.$t('newProject')
  });
  const showProject = ref(false);
  // 状态样式配置
  const statusOptions = ref({
    '编制中': {
      label: '编制中',
      style: {
        color: '#055DD5',
        backgroundColor: '#E7F3FE',
        borderColor: '#66B5FE'
      }
    },
    '未启动': {
      label: '未启动',
      style: {
        color: '#FA8C14',
        backgroundColor: '#FFF7E6',
        borderColor: '#FFA940'
      }
    },
    '正常': {
      label: '正常',
      style: {
        color: '#14AD30',
        backgroundColor: '#EDFFEE',
        borderColor: '#64D26D'
      }
    },
    '延期': {
      label: '延期',
      style: {
        color: '#FA8C14',
        backgroundColor: '#FFF7E6',
        borderColor: '#FFA940'
      }
    },
    // '默认状态': {
    //   label: '默认状态',
    //   style: {
    //     color: '#999',
    //     backgroundColor: '#F5F5F5',
    //     borderColor: '#D9D9D9'
    //   }
    //},
    '完成': {
      label: '完成',
      style: {
        color: '#0B6623',
        backgroundColor: '#C8E6C9',
        borderColor: '#4CAF50'
      }
    },
    '预延期': {
      label: '预延期',
      style: {
        color: '#FA8C14',
        backgroundColor: '#FFF7E6',
        borderColor: '#FFA940'
      }
    },
    '暂停': {
      label: '暂停',
      style: {
        color: '#B8860B',
        backgroundColor: '#FFF3CD',
        borderColor: '#FFC107'
      }
    },
    '延期完成': {
      label: '延期完成',
      style: {
        color: '#7B61FF',      // 深紫色文字
        backgroundColor: '#F3F0FF',  // 淡紫色背景
        borderColor: '#C9BFFF'   // 中紫色边框
      }
    }
  });
  
  const list = ref([
    {
      value: '', // 全部
      label: proxy.$t('label.all')
    },
    {
      value: 'myCreate', // 我创建的
      label: proxy.$t('label.createdByMe')
    },
    {
      value: 'myInCharge', // 我负责的
      label: proxy.$t('label.responsibleByMe')
    },
    {
      value: 'myParticipate', // 我参与的
      label: proxy.$t('label.participateByMe')
    },
    {
      value: 'starred', // 我星标的
      label: proxy.$t('label.starByMe')
    }
  ]);
  const typeList = computed(() => {
    return props.isMy ? list.value.filter(item => item.value) : list.value;
  });
  // 项目查询类型
  const projectOptions = computed(() => {
    return {
      list: typeList.value,
      size: 'large',
      buttonType: 'minor',
      type: 'button'
    };
  });
  // 表格获取数据方法
  const load = (params, callback, exceptionCallback) => {
    let data = {
      ...pick(params, [
        'columns',
        'conditionGroups',
        'conditionJoint',
        'pageNum',
        'pageSize',
        'keyword',
        'needCount',
        'needSort'
      ]),
      typeList: searchTypeList.value
    };

    // 确保pageNum不为0，后端接口期望从1开始
    if (data.pageNum === 0) {
      data.pageNum = 1;
    }
    if (['myCreate', 'myInCharge', 'myParticipate'].includes(operation.value)) {
      data.operation = operation.value;
    }
    if (operation.value === 'starred') {
      data.starred = true;
    }
    if (params.sorts?.sort) {
      data = {
        ...data,
        ...params.sorts
      };
    }
    if (props.isMy) {
      data.filterFlag = 'my';
    }
    const transformCallBack = async res => {
      let statusMap = {};
      const requests = []; // 存储所有异步请求
      if (res?.list?.length) {
        for (const item of res.list) {
          if (item.extAttrMapForSearch) {
            Object.keys(item.extAttrMapForSearch).forEach(key => {
              item[key] = item.extAttrMapForSearch[key];
            });
          }
          if (item.projectManager) {
            item.projectManagerList = item.projectManager.split(',').map(value => ({ value }));
          }
          requests.push(
            axios('/rest/v1/iba/getAttrValueTableByEntitys', {
              method: 'post',
              data: {
                otype: item.otype,
                oidAndLogicalList: [
                  { oid: item.oid, logicalIdentifier: item.otype }
                ],
                isAdapter: true
              },
              headers: {
                authorization: sessionStorage.getItem('authorization')
              }
            }).then(response => {
              if (response.status === 200 && response.data.data) {
                const itemData = response.data.data[item.oid];
                if (itemData?.["执行状态"] && Array.isArray(itemData["执行状态"]) && itemData["执行状态"].length > 0) {
                  statusMap[item.oid] = itemData["执行状态"][0];
                }
              }
            }).catch(error => {
              console.error(`获取项目${item.oid}状态失败：`, error);
            })
          );
          await Promise.all(requests);
        }
        if (isCheckViewPermission.value && getPermByTableData) {
          res.list = await getPermByTableData(res.list);
        }
      }
      callback(res);
      res.list.forEach(item => {
        item.completionStatus = statusMap[item.oid] || '';
      });
      console.log('数据展示',res.list)
    };
    const url = isNewProject.value ? 'queryProjectAdvancedSearch' : 'queryProjectPageByCondition';
    if (isNewProject.value) {
      data.needEmptyCondition = true;
    }
    commandFunc('$rpmapis', 'project', url, data, {
      callback: transformCallBack,
      exceptionCallback
    });
  };
  // 跳转详情
  const goToProjectDetail = row => {
    if (isCheckViewPermission.value && !calcResult2('查看', [row])) {
      return;
    }
    const wujieKey = isNewProject.value ? 'goToNewProjectDetail' : 'goToProjectDetail';
    window.$wujie?.bus.$emit(wujieKey, row);
  };
  // 列配置转换
  const transformColumns = columns => {
    // 先找到里程碑阶段的下标
    const milestoneIdx = columns.findIndex(item => item.field === 'curMileStoneName');
    let newColumns = [...columns];
    if (milestoneIdx !== -1) {
      newColumns.splice(milestoneIdx + 1, 0, {
        field: 'currentStageFinishDate',
        title: '当前阶段完成时间',
        slots: { default: 'column-currentStageFinishDate' },
        width: 129
      });
    } else {
      newColumns.push({
        field: 'currentStageFinishDate',
        title: '当前阶段完成时间',
        slots: { default: 'column-currentStageFinishDate' },
        width: 129
      });
    }
    return [
      {
        type: 'seq',
        title: proxy.$t('table.index'),
        width: 50,
        fixed: 'left'
      },
      {
        field: 'starred',
        title: '',
        slots: { default: 'column-starred' },
        width: 50,
        fixed: 'left'
      },
      ...newColumns.map(item => {
        if (['startDate', 'finishDate'].includes(item.field)) {
          item.formatter = ({ cellValue }) => {
            return cellValue ? dayjs(cellValue).format('YYYY-MM-DD') : '';
          };
        }
        if (['modifystamp', 'createstamp', 'updatestamp'].includes(item.field)) {
          item.formatter = ({ cellValue }) => {
            return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : '';
          };
        }
        return item;
      })
    ];
  };

  // 星标
  const handleStar = row => {
    const callback = () => {
      table.value.tableData = table.value.tableData.map(item => {
        if (item.oid === row.oid) {
          item.starred = !item.starred;
        }
        return item;
      });
    };
    const apiName = row.starred ? 'cancelStarObject' : 'starObject';
    const data = pick(row, ['oid', 'otype']);
    commandFunc('$rpmapis', 'project', apiName, data, {
      callback
    });
  };
  // 刷新表格
  const refresh = () => {
    table?.value?.refresh();
  };
  //批量导入年度计划
  const showModalUploadModal = ref(false);
  const batchImporTnnualPlan = res => {

  }
  // 附件上传
  const batchUploadFile = res => {
    let fileList = projectCreateRef.value?.upload?.fileList;
    fileList = fileList.filter(item => {
      return item.status == 'ready';
    });
    if (fileList?.length) {
      let formData = new FormData();
      let batchUploadDTO = {
        oid: res.oid,
        otype: res.otype,
        updatoroid: sessionStorage.getItem('userID'),
        updatorotype: sessionStorage.getItem('userOtype')
      };
      formData.append('batchUploadDTO', JSON.stringify(batchUploadDTO));
      fileList.forEach(fileRow => {
        formData.append('fileList', fileRow.raw);
      });
      commandFunc('$rpmapis', 'project', 'batchUploadFileUrl', formData);
    }
  };
  // 项目库新建确定回调
  const doConfirm = () => {
    const name = sessionStorage.getItem('userName');
    const fullname = sessionStorage.getItem('userName');
    const oid = sessionStorage.getItem('userID');
    const otype = sessionStorage.getItem('userOtype');
    projectCreateRef.value
      .valideIbaForm()
      .then(valid => {
        if (valid) {
          const formData = projectCreateRef.value.formData;
          const data = pick(formData, [
            'typeOid',
            'typeOtype',
            'name',
            'projectNumber',
            'phase',
            'description',
            'contractDuration',
            'category',
            'completionStatus',
            'ibaAttribute',
            'planTemplateName',
            'planTemplateOID',
            'planTemplateOTYPE'
          ]);
          data.adminUserDescription = fullname;
          data.adminUserName = name;
          data.adminUserOid = oid;
          data.adminUserOtype = otype;
          data.updatorName = name;
          data.updatorOID = oid;
          data.updatorOTYPE = otype;
          if (!data.completionStatus) {
            data.completionStatus = 0;
          }
          const planDate = formData.planDate;
          if (planDate.length === 2) {
            data.startDate = `${dayjs(planDate[0]).format('YYYY-MM-DD')} 00:00:00`;
            data.finishDate = `${dayjs(planDate[1]).format('YYYY-MM-DD')} 23:59:59`;
          }
          if (formData?.owner?.length) {
            const user = formData.owner[0];
            const { name, fullname, oid, otype } = user;
            data.ownerDescription = fullname;
            data.ownerName = name;
            data.ownerOID = oid;
            data.ownerOTYPE = otype;
          }
          if (formData?.projectManagerList?.length) {
            data.projectManagerList = formData.projectManagerList.map(item => {
              return {
                oid: item.oid,
                otype: item.otype,
                description: item.fullname,
                name: item.name
              };
            });
          }
         const { templateStartDate, templateFinishDate, resousceFalg } = formData.projectTemplateObj;
          data.projectTemplateObj = {
            curPeriod: computerPeriod(data.startDate, data.finishDate),
            templateStartDate: templateStartDate ? dayjs(templateStartDate).format('YYYY-MM-DD HH:mm:ss') : '',
            templateFinishDate: templateFinishDate ? dayjs(templateFinishDate).format('YYYY-MM-DD HH:mm:ss') : '',
            templatePeriod: computerPeriod(data.startDate, data.finishDate),
            resousceFalg: resousceFalg || false
          };
          data.checked = resousceFalg;
          data.extPropsObj = {
            productTempalte: ''
          };
          data.extProps = '';
          if (templateStartDate && templateFinishDate) {
            data.projectTemplateObj.templatePeriod = computerPeriod(templateStartDate, templateFinishDate);
          }
 
          // data.planTemplateOTYPE='ty.inteplm.project.CTyProject';
          const callback = res => {
            proxy.$message.success(`${proxy.$t('newProject')}${proxy.$t('success')}`);
            projectCreateOptions.value.confirmLoading = false;
            showProject.value = false;
            refresh();
            batchUploadFile(res);
          };
          const exceptionCallback = error => {
            projectCreateOptions.value.confirmLoading = false;
            if (error?.data?.message) {
              proxy.$message.error(error.data.message);
            }
          };
          projectCreateOptions.value.confirmLoading = true;
          commandFunc('$rpmapis', 'project', 'insertProjectForPdmWithFolderPath', data, {
            callback,
            exceptionCallback
          });
        }
      })
      .catch(() => {
        projectCreateOptions.value.confirmLoading = false;
      });
  };
  // 新建项目库
  const create = () => {
    if (isNewProject.value) {
      window.$wujie?.bus.$emit(`${wujieName}createProject`);
    } else {
      showProject.value = true;
    }
  };
  /**
   * @description 保存用户列配置
   * @return { }
   * @Date 2024-03-19 09:15:31
   * @Author hujingshan hujs@tysoft.com
   */
  const saveColumns = searchColumnList => {
    const data = {
      ...table.value.userDefaultTableView,
      searchColumnList
    };
    if (data?.searchCondition?.columns) {
      data.searchCondition.columns = searchColumnList;
    }
    if (data?.info?.columnDisplay) {
      data.info.columnDisplay = searchColumnList.map(item => item.displayName).join('、');
    }
    commandFunc('$rpmapis', 'project', 'saveUserDefaultTableView', data);
  };
  // 离开页面保存列配置
  window.$wujie?.bus.$on('projectList', isMy => {
    if (((props.isMy && isMy) || (!props.isMy && !isMy)) && table.value) {
      table.value.setcurrentColumnListWidth();
      const searchColumnList = table.value.currentColumnList;
      sessionStorage.setItem('currentColumnList', JSON.stringify(searchColumnList));
      if (searchColumnList.length) {
        saveColumns(searchColumnList);
      }
    }
    if ((props.isMy && !isMy) || (!props.isMy && isMy)) {
      setTimeout(() => {
        if (table.value) {
          const searchColumnList = JSON.parse(sessionStorage.getItem('currentColumnList'));
          table.value.currentColumnList = searchColumnList;
          table.value.refreshColumns(searchColumnList);
        }
      }, 0);
    }
  });

  watch(
    () => window.$wujie?.props,
    val => {
      if (val?.path == '/projectList') {
        isNewProject.value = true;
      } else {
        isNewProject.value = false;
      }
    },
    {
      immediate: true
    }
  );
  onMounted(async () => {
    searchTypeList.value = await getTypeList(types.value);
    window.$wujie?.bus.$on('refreshProjectList', () => {
      refresh();
    });
  });
  return {
    isPMO,
    operates,
    searchTypeList,
    table,
    projectCreateRef,
    operation,
    projectCreateOptions,
    showProject,
    statusOptions,
    projectOptions,
    load,
    goToProjectDetail,
    transformColumns,
    handleStar,
    refresh,
    doConfirm,
    create,
    sortColumns,
    isCheckViewPermission,
    calcResult2,
    defaultCondition,
    batchImporTnnualPlan,
    showModalUploadModal
  };
};
